import storage from 'store'
import { login, register,logout } from '@/api/login'
import { detail } from '@/api/user/index'

const ACCESS_TOKEN = 'Access-Token'
const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: {},
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {

    // 用户登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(response => {
            const data = response.data;
            // token保存7天
            storage.set(ACCESS_TOKEN, data.token, 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', data.token)
            commit('SET_INFO', data.user);
            resolve(response)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 用户注册
    Register ({ commit }, from) {
      return new Promise((resolve, reject) => {
        register(from)
          .then(response => {
            const data = response.data;
            // token保存7天
            storage.set(ACCESS_TOKEN, data.token, 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', data.token)
            commit('SET_INFO', data.user)
            resolve(response)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    
    // 退出登录
    Logout ({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then((result) => {
            // 清理用户信息
            commit('SET_TOKEN', '')
            commit('SET_INFO', {})
            storage.remove(ACCESS_TOKEN)
            resolve(result)
          })
      })
    },

    // 获取用户信息
    GetInfo ({ commit },from) {
      return new Promise((resolve, reject) => {
        detail(from).then(response => {
          const data = response.data
          commit('SET_INFO', data.userInfo);
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 超管后台自动登录
    SuperLogin ({ commit }, loginInfo) {
      // token保存7天
      storage.set(ACCESS_TOKEN, loginInfo['token'], 7 * 24 * 60 * 60 * 1000)
      commit('SET_TOKEN', loginInfo['token'])
    }

  }
}

export default user
